from app import db, login_manager
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin

class Customer(db.Model):
    """客户信息表"""
    __tablename__ = 'customers'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)  # 客户名称
    phone = db.Column(db.String(20))                  # 联系电话
    vehicles = db.relationship('Vehicle', backref='owner', lazy=True)  # 添加与车辆的关联
    orders = db.relationship('Order', backref='customer', lazy=True)

class Vehicle(db.Model):
    """车辆信息表"""
    __tablename__ = 'vehicles'
    
    id = db.Column(db.Integer, primary_key=True)
    model = db.Column(db.String(100))          # 汽车类型
    plate_number = db.Column(db.String(20), unique=True)  # 车牌号码
    notes = db.Column(db.Text)                 # 备注信息
    customer_id = db.Column(db.Integer, db.ForeignKey('customers.id'))  # 添加车主ID
    orders = db.relationship('Order', backref='vehicle', lazy=True)

class Order(db.Model):
    """维修销售订单表"""
    __tablename__ = 'orders'
    
    id = db.Column(db.Integer, primary_key=True)
    order_number = db.Column(db.String(50), unique=True)  # 单号
    customer_id = db.Column(db.Integer, db.ForeignKey('customers.id'))
    vehicle_id = db.Column(db.Integer, db.ForeignKey('vehicles.id'))
    created_at = db.Column(db.DateTime, default=datetime.now)  # 开单时间
    total_amount = db.Column(db.Float)         # 合计金额
    operator = db.Column(db.String(50))        # 操作员
    status = db.Column(db.String(20), default='待维修')  # 维修状态：待维修、维修中、已完成、已取消
    repair_notes = db.Column(db.Text)          # 维修备注
    completed_at = db.Column(db.DateTime)      # 完成时间
    items = db.relationship('OrderItem', backref='order', lazy=True)

class Part(db.Model):
    """配件表"""
    __tablename__ = 'parts'
    
    id = db.Column(db.Integer, primary_key=True)
    part_number = db.Column(db.String(50))     # 配件编号
    name = db.Column(db.String(100))           # 配件名称
    unit = db.Column(db.String(20))            # 单位
    cost_price = db.Column(db.Float)           # 进价
    price = db.Column(db.Float)                # 售价

class OrderItem(db.Model):
    """订单明细表"""
    __tablename__ = 'order_items'
    
    id = db.Column(db.Integer, primary_key=True)
    order_id = db.Column(db.Integer, db.ForeignKey('orders.id'))
    part_id = db.Column(db.Integer, db.ForeignKey('parts.id'))
    quantity = db.Column(db.Integer)           # 数量
    price = db.Column(db.Float)                # 单价
    amount = db.Column(db.Float)               # 总金额
    
    # 添加与配件的关联关系
    part = db.relationship('Part', backref='order_items', lazy=True) 

class User(UserMixin, db.Model):
    """用户表"""
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    mobile = db.Column(db.String(20), unique=False, nullable=True)
    password_hash = db.Column(db.String(128))
    name = db.Column(db.String(80))  # 真实姓名
    role = db.Column(db.String(20))  # admin/staff
    active = db.Column(db.Boolean, default=True)
    
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)
        
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)
    
    def has_role(self, role):
        return self.role == role
    
    def to_dict(self):
        return {
            'id': self.id,
            'username': self.username,
            'mobile': self.mobile,
            'name': self.name,
            'role': self.role,
            'active': self.active
        }

@login_manager.user_loader
def load_user(id):
    return User.query.get(int(id)) 